<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="收件人" prop="consignee">
            <el-input v-model="ruleForm.consignee"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber">
            <el-input v-model="ruleForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="选择地区" prop="region">
            <el-cascader size="large" :options="pcaTextArr" v-model="ruleForm.region">
            </el-cascader>
        </el-form-item>
        <el-form-item label="地址" prop="address">
            <el-input v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                添加
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>

    <el-table :data="addressList" style="width: 100%">
        <el-table-column label="地址" prop="address" width="800">
        </el-table-column>
        <el-table-column label="操作">
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>


    <el-dialog v-model="dialogFormVisible" title="修改地址">
        <el-form v-model="form" label-width="120px">
            <el-form-item label="收件人">
                <el-input v-model="form.consignee" ></el-input>
            </el-form-item>

            <el-form-item label="电话号码">
                <el-input v-model="form.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="选择地区">
                <el-cascader size="large" :options="pcaTextArr" v-model="form.region">
                </el-cascader>
            </el-form-item>
            <el-form-item label="地址">
                <el-input v-model="form.detailAddress"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="editAddress()">
                    修改
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import { FormInstance, FormRules, ElNotification } from 'element-plus'
import { pcaTextArr } from 'element-china-area-data'
import api from '@/api'
import store from '@/store';

interface RuleForm {
    region: [],
    address: '',
    consignee: '',
    phoneNumber: ''
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    region: [],
    address: '',
    consignee: '',
    phoneNumber: ''
})

const rules = reactive<FormRules<RuleForm>>({
    region: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'blur',
        },
    ],
    address: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'blur',
        },
    ],
    consignee: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'blur',
        },
    ],
    phoneNumber: [
        {
            required: true,
            message: 'Please select Activity zone',
            trigger: 'blur',
        },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.address.addAddress({ region: ruleForm.region, address: ruleForm.address, userId: store.getters.getUserInfo.id, consignee: ruleForm.consignee, phoneNumber: ruleForm.phoneNumber })
                .then(response => {
                    // 在这里可以处理提交成功后的逻辑

                    ElNotification({
                        title: 'Success',
                        message: response.data.msg,
                        type: 'success',
                        duration: 1500
                    })

                })
                .catch(error => {
                    ElNotification({
                        title: 'Error',
                        message: error.data.msg,
                        type: 'error',
                        duration: 1500
                    })
                    // 在这里可以处理提交失败后的逻辑
                });

        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}



const handleEdit = (index: number, row: any) => {
    form.id = row.id
    api.address.getAddressById({ id: row.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            form.consignee = response.data.data.consignee
            form.id = response.data.data.id
            form.detailAddress = response.data.data.detailAddress
            form.phoneNumber = response.data.data.phoneNumber
            form.region = [];
            form.region.push(response.data.data.province);
            form.region.push(response.data.data.city);
            form.region.push(response.data.data.district);
            dialogFormVisible.value = true
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}
const handleDelete = (index: number, row: any) => {
    api.address.deleteAddress({id:row.id,userId:store.getters.getUserInfo.id})
    .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getAddressByUserId()
            dialogFormVisible.value = false
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

const addressList = ref([
    {

    }
])

onMounted(() => {
    getAddressByUserId()
})

function getAddressByUserId() {
    api.address.getAddressByUserId({ userId: store.getters.getUserInfo.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            addressList.value = response.data.data

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}


const dialogFormVisible = ref(false)

const form = reactive({
    region: [''],
    consignee: '',
    phoneNumber: '',
    id: '',
    detailAddress: '',
    userId: store.getters.getUserInfo.id 
})



function editAddress() {
    api.address.editAddress(form)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getAddressByUserId()
            dialogFormVisible.value = false
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })

        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}
</script>
<style scoped>
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>